'use strict';

const Controller = require('egg').Controller;

class BlogController extends Controller {
    //添加
    async create() {
        let {ctx,service} = this;

        let {title,con} = ctx.request.body;

        console.log(ctx.info)

        let {id} = ctx.info;

        if(title && con){
            try{
                await service.blog.add(title,con,id);
                ctx.body = {
                    code:1,
                    msg:'发表成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //删除
    async destroy(){
        let {ctx,service} = this;
        let uid = ctx.info.id;
        let {id} = ctx.params;

        if(id){
            try{
                console.log(id,uid);
                let info = await service.blog.del(id,uid);
                console.log(info)
                if(info.affectedRows){
                    ctx.body = {
                        code:1,
                        msg:'删除成功'
                    }
                }else{
                    ctx.body = {
                        code:3,
                        msg:'此博客不存在'
                    }
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //编辑
    async update(){
        let {ctx,service} = this;

        let {title,con} = ctx.request.body;

        let {id} = ctx.params;  //编辑博客id

        let uid = ctx.info.id;  //用户的id

        if(title && con && id){
            try{
                await service.blog.edit(title,con,uid,id);
                ctx.body = {
                    code:1,
                    msg:'编辑成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //查询
    async index(){
       let {ctx,service} = this; 
       let list = await service.blog.bloglist();
       ctx.body = {
           code:1,
           data:list
       }
    }
}

module.exports = BlogController;
